package com.it.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.it.entity.Inventory;
import com.it.entity.InventoryInfo;
import com.it.entity.Product;
import com.it.service.ProductService;
import com.it.util.Result;
import com.it.util.ResultResponse;
import com.it.util.TableResultResponse;
import com.it.vo.InventoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：〈库存管理相关接口/控制器〉
 */
@Controller
@RequestMapping("/inventory")
public class InventoryController {
    @Autowired
    private com.it.service.InventoryService InventoryService;
    @Autowired
    private ProductService productService;

    /**
     * 库存管理首页页面跳转
     * （将数据库中所有的菜单信息查询出来封装好传给前台，前台通过
     * layui-tree插件现实菜单数据）
     *
     * @param mv
     * @return
     */
    @RequestMapping("/index.do")
    public ModelAndView index(ModelAndView mv) {
        mv.setViewName("/inventory/index");
        return mv;
    }

    /**
     * 入库记录管理页面跳转
     * （将数据库中所有的菜单信息查询出来封装好传给前台，前台通过
     * layui-tree插件现实菜单数据）
     *
     * @param mv
     * @return
     */
    @RequestMapping("/info.do")
    public ModelAndView info(ModelAndView mv) {
        mv.setViewName("/inventory/info");
        return mv;
    }

    /**
     * 库存管理界面列表异步加载
     *
     * @param Inventory 查询对象
     * @param page      当前页数
     * @param limit     查询数据条数
     * @return
     */
    @ResponseBody
    @GetMapping("inventory.do")
    public TableResultResponse reloadTable(int page, int limit, Inventory Inventory) {
        List<Map<String, Object>> infoList = new ArrayList<>();
        Page<com.it.entity.Inventory> pageInfo = InventoryService.selectPage(Inventory, page, limit);
        for (com.it.entity.Inventory record : pageInfo.getRecords()) {
            Map<String, Object> resultMap = new HashMap<>(16);
            resultMap.put("id", record.getId());
            resultMap.put("productUuId", record.getProductUuId());
            Product product = productService.getOne(record.getProductId());
            resultMap.put("productName", product.getName());
            resultMap.put("stock", record.getStock());
            resultMap.put("sale", record.getSale());
            resultMap.put("unitPrice", record.getUnitPrice());
            resultMap.put("zumPrice", record.getZumPrice());
            infoList.add(resultMap);
        }
        return Result.tableResule(pageInfo.getTotal(), infoList);
    }

    /**
     * 入库记录管理界面列表异步加载
     *
     * @param inventoryInfo 查询对象
     * @param page          当前页数
     * @param limit         查询数据条数
     * @return
     */
    @ResponseBody
    @GetMapping("inventoryInfo.do")
    public TableResultResponse infoReloadTable(int page, int limit, InventoryInfo inventoryInfo) {
        List<Map<String, Object>> infoList = new ArrayList<>();
        Page<InventoryInfo> pageInfo = InventoryService.selectPage(inventoryInfo, page, limit);
        for (InventoryInfo record : pageInfo.getRecords()) {
            Map<String, Object> resultMap = new HashMap<>(16);
            resultMap.put("id", record.getId());
            resultMap.put("productUuId", record.getProductUuId());
            resultMap.put("productName", record.getProductName());
            resultMap.put("specification", record.getSpecification());
            resultMap.put("stock", record.getStock());
            resultMap.put("supplier", record.getSupplier());
            resultMap.put("costPrice", record.getCostPrice());
            resultMap.put("salePrice", record.getSalePrice());
            resultMap.put("content", record.getContent());
            resultMap.put("userName", record.getUserName());
            resultMap.put("time", record.getTime() == null ? "" : record.getTime().substring(0, 19));
            infoList.add(resultMap);
        }
        return Result.tableResule(pageInfo.getTotal(), infoList);
    }

    /**
     * 药品入库页面弹窗
     *
     * @return
     */
    @RequestMapping("/addPage.do")
    public ModelAndView addPage(ModelAndView mv) {
        mv.setViewName("/inventory/addPage");
        return mv;
    }

    /**
     * 药品入库
     *
     * @param inventoryVo
     * @return
     */
    @PostMapping("/inventory.do")
    @ResponseBody
    public ResultResponse insert(InventoryVo inventoryVo) {
        //创建插入库存数据对象
        Inventory inventory = new Inventory();
        //创建插入库存记录数据对象
        InventoryInfo inventoryInfo = new InventoryInfo();
        boolean result = false;
        //查询药品信息
        Product product = productService.getOne(inventoryVo.getProductId());
        inventory.setProductId(inventoryVo.getProductId());
        inventory.setProductUuId(product.getUuId());
        inventory.setUnitPrice(product.getDisPrice());
        inventory.setZumPrice(product.getDisPrice() * inventoryVo.getStock());
        //查询该药品是否已经入库
        Inventory checkHave = InventoryService.checkHave(inventoryVo.getProductId());
        if (checkHave != null) {
            //该药品已经入过库.则修改该信息
            inventory.setId(checkHave.getId());
            inventory.setStock(inventoryVo.getStock() + checkHave.getStock());
            result = InventoryService.editById(inventory);
        } else {
            inventory.setStock(inventoryVo.getStock());
            inventory.setSale(0);
            result = InventoryService.insert(inventory);
        }
        if (!result) {
            return Result.resuleError("新增失败");
        }
        //新增库存信息成功后新增入库记录信息
        inventoryInfo.setProductUuId(product.getUuId());
        inventoryInfo.setProductName(product.getName());
        inventoryInfo.setSalePrice(product.getDisPrice());
        inventoryInfo.setSpecification(product.getSpecification());
        inventoryInfo.setStock(inventoryVo.getStock());
        inventoryInfo.setSupplier(inventoryVo.getSupplier());
        inventoryInfo.setCostPrice(inventoryVo.getCostPrice());
        inventoryInfo.setContent(inventoryVo.getContent());
        InventoryService.insert(inventoryInfo);
        return Result.resuleSuccess();
    }

    /**
     * 删除库存信息
     *
     * @param id
     * @return
     */
    @DeleteMapping("/inventory.do")
    @ResponseBody
    public ResultResponse delete(String id) {
        boolean result = InventoryService.deleteById(id);
        if (!result) {
            return Result.resuleError("删除失败");
        }
        return Result.resuleSuccess();
    }

    /**
     * 删除入库记录信息
     *
     * @param id
     * @return
     */
    @DeleteMapping("/inventoryInfo.do")
    @ResponseBody
    public ResultResponse deleteInfo(String id) {
        boolean result = InventoryService.deleteInfoById(id);
        if (!result) {
            return Result.resuleError("删除失败");
        }
        return Result.resuleSuccess();
    }

    /**
     * 入库弹框中查询药品页面
     *
     * @return
     */
    @RequestMapping("/productListPage.do")
    public ModelAndView productListPage(ModelAndView mv) {
        mv.setViewName("/inventory/productListPage");
        return mv;
    }

    /**
     * 验证药品是否还有库存
     *
     * @param productId
     * @return
     */
    @PostMapping("/haveStock.do")
    @ResponseBody
    public ResultResponse haveStock(String productId, Integer num) {
        Product product = productService.getOne(productId);
        Inventory inventory = InventoryService.checkHave(productId);
        Integer stock = 0;
        if (inventory != null) {
            stock = inventory.getStock();
        }
        if (num > stock) {
            return Result.resuleError("药品:" + product.getName() + "  库存不足!");
        }
        return Result.resuleSuccess();
    }
}